Practice | GeeksforGeeks | A computer science portal for geeks
LIVE   BATCHES
We have combined Classroom and Theory tab and created a new Learn tab for easy access. You can access Classroom and Theory from the left panel.

How Function Works
 

Loops in CPP

For Loop in CPP
There come situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code.

Decision making statements in programming languages decides the direction of flow of program execution. Decision making statements available in C++ are:

if statement

if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if(condition) 
{
// Statements to execute if
// condition is true
}
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the first immediately below statement to be inside its block.
Example:
if(condition)
statement1;
statement2;

// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.
Flowchart:
if-statement-in-java

// C++ program to illustrate If statement
#include<iostream>
using namespace std;
int main()
{
int i = 10;
if (i > 15)
{
cout<<"10 is less than 15";
}
cout<<"I am Not in if";
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is not executed.

if- else

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart:
if-else-statement
Example:
// C++ program to illustrate if-else statement
#include<iostream>
using namespace std;
int main()
{
int i = 20;
if (i < 15)
cout<<"i is smaller than 15";
else
cout<<"i is greater than 15";
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
i is greater than 15
The block of code following the else statement is executed as the condition present in the if statement is false.

nested-if

A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement. Yes, C++ allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1) 
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Flowchart:
nested-if
Example:
// C++ program to illustrate nested-if statement
int main()
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
cout<<"i is smaller than 15";
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
cout<<"i is smaller than 12 too";
else
cout<<"i is greater than 15";
}
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
i is smaller than 15
i is smaller than 12 too

if-else-if ladder

Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
if-else-if-ladder
Example:
// C++ program to illustrate if-else-if ladder
#include<iostream>
using namespace std;
int main()
{
int i = 20;
if (i == 10)
cout<<"i is 10";
else if (i == 15)
cout<<"i is 15";
else if (i == 20)
cout<<"i is 20";
else
cout<<"i is not present";
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
i is 20

Switch-case

Switch case statements are a substitute for long if statements that compare a variable to several integral values.
  • The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
  • Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}
switch-case-in-java
Example:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 2;
switch (x)
{
case 1: cout << "Choice is 1\n";
break;
case 2: cout << "Choice is 2\n";
break;
case 3: cout << "Choice is 3\n";
break;
default: cout << "Choice other than 1, 2 and 3\n";
break;
}
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
Choice is 2

Looping Statements


Loops in programming come into use when we need to repeatedly execute a block of statements. For example: Suppose we want to print "Hello World" 10 times. This can be done in two ways as shown below:

Iterative Method

An iterative method to do this is to write the cout statement 10 times.

// C++ program to illustrate need of loops
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Using Loops

In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below.
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.
  • An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.
  • Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeat it.
  • Counter reached: If the condition has been reached, the next instruction "falls through" to the next sequential instruction or branches outside the loop.
There are mainly two types of loops:
  1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop body. For Loop and While Loop are entry controlled loops.
  2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of loop body. Therefore, the loop body will execute atleast once, irrespective of whether the test condition is true or false. do - while loop is exit controlled loop.

for Loop

A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated. Steps are repeated till exit condition comes.
  • Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: int i=1;
  • Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: i <= 10;
  • Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: i++;


Equivalent flow diagram for loop :


Example:
// C++ program to illustrate for loop
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

While Loop

While studying for loop we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. while loops are used in situations where we do not know the exact number of iterations of loop beforehand. The loop execution is terminated on the basis of the test condition.

Syntax:
We have already stated that a loop is mainly consisted of three statements - initialization expression, test expression, update expression. The syntax of the three loops - For, while and do while mainly differs on the placement of these three statements.
initialization expression;
while (test_expression)
{
// statements

update_expression; }

Flow Diagram:


Example:
// C++ program to illustrate for loop
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
Hello World
Hello World
Hello World
Hello World
Hello World


do while loop

In do while loops also the loop execution is terminated on the basis of test condition. The main difference between do while loop and while loop is in do while loop the condition is tested at the end of loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.

Syntax:
initialization expression;
do
{
// statements

update_expression; } while (test_expression);
Note: Notice the semi - colon(";") in the end of loop.

Flow Diagram:


Example:
// C++ program to illustrate do-while loop
#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout << "Hello World\n";
// update expression
i++;
} while (i < 1); // test expression
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
Hello World

In the above program the test condition (i<1) evaluates to false. But still as the loop is exit - controlled the loop body will execute once.


What about an Infinite Loop?

An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition always evaluates to true. Usually, this is an error.
// C++ program to demonstrate infinite loops using for and while Uncomment the sections to see the output
#include <iostream>
using namespace std;
int main (){
int i;
// This is an infinite for loop as the condition
// expression is blank
for ( ; ; ) {
cout << "This loop will run forever.\n";
}
// This is an infinite for loop as the condition
// given in while loop will keep repeating infinitely
/*
while (i != 0){
i-- ;
cout << "This loop will run forever.\n";
}
*/
// This is an infinite for loop as the condition
// given in while loop is "true"
/*
while (true)
{
cout << "This loop will run forever.\n";
}
*/
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
This loop will run forever.
This loop will run forever.
...................

Important Points:
  • Use for loop when number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known.
  • Use while loops where exact number of iterations is not known but the loop termination condition is known.
  • Use do while loop if the code needs to be executed at least once like in Menu driven programs



Jump Statements

Jump statements help programmers to jump directly to a point in program breaking the normal flow of execution. They provide change in program execution flow. There are 3 jump constructs in C/C++:
  • break: Break statements are used to terminate a loop. Thus the flow jumps directly to the 1st statement after the loop upon encountering a break statement.

    As an example of linear search in an array, we want to quit looking further once we found the element we desire.
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
    int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int key = 5;
    for (int i = 0; i < 10; i++) {
    if (arr[i] == key) {
    cout << "5 found in array";
    break;
    }
    }
    return 0;
    }
    הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    Output:
    5 found in array
  • continue: Continue statements force the execution of the next iteration of the loop disregarding the statements following it.i.e. when a continue is encountered, all the statements following are skipped and control returns to the next iteration (condition check).

    As an example:
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
    for (int i = 1; i <= 10; i++) {
    if (i == 6) //If i equals 6, continue to next
    //iteration without printing
    continue;
    cout << i << " ";
    }
    return 0;
    }
    הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    Output:
    1 2 3 4 5 7 8 9 10 
  • goto: It is a statement which enables us to jump anywhere in a program. Unlike break and continue, which interrupts the flow of a loop. i.e. they have scope to jump within a loop (terminate or force next iteration), goto has the capability to reach anywhere in the program. goto works with the concept of labels. A label is a named block of code. It will be clear from the example given below. First, the syntax looks as:
    Syntax1      |   Syntax2
    ----------------------------
    goto label; | label:
    . | .
    . | .
    . | .
    label: | goto label;
    As can be seen from the above syntax, the label can exist anywhere in the program (prior or after). Upon encountering the goto label; statement, flow jumps to the label unconditionally.
    goto
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
    int n = 1;
    label:
    cout << n << " ";
    n++;
    if (n <= 5)
    goto label;
    return 0;
    }
    הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    Output:
    1 2 3 4 5
    In the above program, each time goto is encountered, execution jumps back to label.
    goto statements are deemed too powerful and hence are discouraged because of the following reasons:
    • Makes program logic very complex (harder to debug & modify).
    • Usage of goto can be easily substituted with the more safe continue & break statements.
A function is a set of statements that take inputs, do some specific computation and produce output.

The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. The syntax for a function is as follows:
< return-type > < function-name > (< set-of-arguments >) {
//block of statements
}
As an example:
#include <bits/stdc++.h>
using namespace std;
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
int main()
{
int a = 10, b = 20;
// Calling above function to find max of 'a' and 'b'
int m = max(a, b);
cout << "Maximum of a & b is: " << m;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
Maximum of a & b is: 20

Note: Regarding the return-type, every function needs to return a value matching the type if return-type is declared anything other than void. In case of void return type, no return statement is required.

Prototype Declaration & Definition

Sometimes, we just want to declare the existence of a function and provide the implementation afterwards. We can do so by using the prototype-declaration scheme, the syntax of which is given below:
< return-type > < function-name > (< set-of-arguments >);
As an example:
int max(int a, int b);
int min(int, int); // we don't even have to name
// our argument variables
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Once declared, we can define (provide implementation) anywhere in the program. (or even in another file, if the function is declared extern).

Formal & Actual Parameters

The parameters passed to function are called actual parameters. For example, in the first program 10 and 20 are actual parameters. The parameters received by function are called formal parameters. For example, in the above program x and y are formal parameters.

Pass by value & Pass by Reference

There are two types of passing arguments to functions. The arguments declared within the function (formal parameter variables) have function block scope only. Hence, any manipulation done on them has no effect on the actual variables with which the function was called. This will be clear with the following Pass by value example:
#include <bits/stdc++.h>
using namespace std;
void swap(int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 5, b = 6;
swap(a, b);
cout << "a: " << a << ", b: " << b <<endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
a: 5, b: 6
As we can see, the values inside of main don't get swapped. This is because they were passed by value. Hence, any change done inside the function isn't reflected in the main() part. This is because in pass-by-value, the value and not the actual memory location gets copied to the formal parameters in the function.
Pass by Reference on the other hand manipulates with the memory location of actual parameters, thus reflecting the changes made inside the function to the actual variables. There are again 2 ways to pass-by-reference in C++, using:
  • Native C pointers - We shall cover this when we discuss pointers.
  • C++ References - Reference is the C++ way of passing arguments by reference. The syntax to use is as follows.
    int swap(int &a, int &b) { ... } 
    //add & before the parameters (call-by-reference)
    ...
    int a = 5, b = 6;
    swap(a, b); //calling the function remains the same
The same above program using call-by-reference yields output as:
#include <bits/stdc++.h>
using namespace std;
void swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 5, b = 6;
swap(a, b);
cout << "a: " << a << ", b: " << b <<endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Output:
a: 6, b: 5
So, the elements get swapped in real.

Inline Functions

Inline functions are an improvement provided by C++ to reduce the overhead caused in executing a function call. A function call statement is a jump statement that instructs the program counter to switch to a different address for execution. In a function call, a lot of work that the OS needs to be done such as storing the current address of execution (to return back to), along with other registers. Also, allocation and de-allocation (upon exit) of variables local to the functions are done. This can greatly hamper performance if a function is called repeatedly in a program. e.g. frequently called utility functions such as min(), max(), or in case of recursive functions such as factorial().
Inline functions reduce this overhead by replacing the function definition at the place of the function call. i.e. inline-functions are expanded at the call location itself during compilation. This removes the function call overhead at the cost of a larger compilation code. As an example:
#include <bits/stdc++.h>
using namespace std;
inline int max_int(int x, int y) { return (x > y) ? x : y; }
int main()
{
cout << max_int(5, 6) << endl;
cout << max_int(8, 7) << endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
6
8
When the program compiles, the definition is expanded as:
cout << (5 > 6) ? 5 : 6 << endl;
cout << (8 > 7) ? 8 : 7 << endl;
If there are multiple calls to max_int function, usage of inline can greatly improve performance. However, there is an added downside of increased compilation code size, because of inline-expansion. Thus, it is advised to make only those functions inline which are short & frequently used.

Default Arguments

A Default Argument is a default value for a function argument. In case the user forgets to provide the parameter, the default value for that variable would be used. As an example:
#include <bits/stdc++.h>
using namespace std;
int add(int x, int y=0)
{
return x+y;
}
int main()
{
cout << add(5, 6) << endl;
cout << add(5) << endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
11
5
There is an important rule in declaring default parameters: No non-default (mandatory) argument can follow a default argument. The direct consequence of this rule is that all default arguments must follow non-default ones:
int add(int y=10, int x);   //not allowed
int add(int x, int y=10); //allowed
as a call to a function like add( , 3) is not allowed in C++. Rather add(3) is valid. So, all default params should follow the non-default ones.

Function Overloading

Function overloading allows us to create functions with different names, as long as they have different parameters. As an example:
#include <bits/stdc++.h>
using namespace std;
int add(int x, int y) { return x + y; }
string add(string x, string y) { return x + y; }
int main()
{
//adds the 2 numbers
cout << add(5, 6) << endl;
//concatenates the 2 strings
cout << add("Hello ", "World") << endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
11
Hello World
There are some important rules for overloading functions:
  • Return-Type is not a factor for uniqueness: Return-Type plays no role in resolving ambiguity of overloaded functions. Thus, two functions declared exactly the same with only the return-type different will generate a compilation error.
    int add(int, int);
    double add(int, int);
    //generates Compilation Error
    הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  • Argument Names are not a factor for uniqueness: Similar to above, declaring argument names differently with their types same also doesn't resolve ambiguity.
    int add(int a, int b);
    double add(int c, int d);
    //generates Compilation Error
    הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Function Pointers

Functions are an executable block of code which is placed at a certain address when a program is loaded into memory. e.g. If we execute the code below:
#include <bits/stdc++.h>
using namespace std;
int add(int x, int y) { return x + y; }
int main()
{
cout << add << endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
0x002717f0
On author's machine, the above address gets printed. It may vary depending upon implementation. However, the crux of the matter to understand is that upon printing the function name only without paranthesis. i.e. add, instead of add(), we get the address to the function. Function Pointers is a facility provided in C/C++ to declare pointers to functions. The syntax for declaration is as follows:
< return-type > (* < function-name >)(< argument-list >);
Example:
#include <bits/stdc++.h>
using namespace std;
int add(int x, int y) { return x + y; }
string add(string x, string y) { return x + y; }
int main()
{
//Assign integer add() function to funtion pointer
int (*fun_ptr_int)(int, int) = add;
//Assign string add() function to function pointer
string (*fun_ptr_str)(string, string) = add;
//Calling using function pointer
cout << fun_ptr_int(5, 6) << endl;
cout << fun_ptr_str("Hello ", "World") << endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
11
Hello World
NOTE: The return-type and argument signature of the function must exactly match the function pointer declaration. e.g. Following are some valid and invalid assignments:
int fun1();
double fun2();
int fun3(int);
int (*fun_ptr)() = fun1; //valid
fun_ptr = fun2; //invalid (return-type mismatch)
fun_ptr = fun3; //invalid (argument list mismatch)
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
A best case example of using function pointers is when we need to pass function as an argument to another function. Consider a sorting function which we want to sort numbers both ascending and descending order, given 2 seperate functions for comparing numbers. We can do so by using function pointers as:
#include <bits/stdc++.h>
using namespace std;
//3rd argument is a function pointer
void sort(int a[], int n, bool (*compare)(int, int)){
int i,j;
for (i=0; i<n-1; i++)
for (j=0; j<n-i-1; j++)
if (!compare(a[j], a[j+1]))
swap(a[j], a[j+1]);
}
bool asc(int x, int y) { return x < y; }
bool desc(int x, int y) { return x > y; }
int main(){
int a[] = {0, 2, 5, 6, 9, 1, 3, 4, 8, 7};
//pass ascending function
sort(a, 10, asc);
for (int i=0; i<10; i++)
cout << a[i] << " ";
cout << endl;
//pass descending function
sort(a, 10, desc);
for (int i=0; i<10; i++)
cout << a[i] << " ";
cout << endl;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
0 1 2 3 4 5 6 7 8 9 
9 8 7 6 5 4 3 2 1 0

Variable Arguments

One might have seen functions such as printf, scanf which are capable of printing/scanning any number of input arguments provided. This is achieved by using variable arguments. The advantage of having a variable argument feature in C++ is to have functions which can operate on any number of arguments and produce the result. e.g. Suppose we want a function that can take the average of any number of integers passed:
#include <bits/stdc++.h>
using namespace std;
double average(int num, ...) {
va_list args;
double sum = 0;
va_start(args, num);
for (int i = 0; i < num; i++)
sum += va_arg(args, double);
va_end(args);
return sum / num;
}
int main()
{
cout << average (3, 1, 2, 3) <<endl;
cout << average (5, 1, 2, 3, 4, 5) <<endl;
return 0;
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Output:
6.95312e-310
4.16905e-310
Some of the important syntax and keywords used in the code:
  • Usage of ... in function argument: This spread operator is the indication of declaring the function as accepting variable arguments.
  • va_list: Stores the list of variable arguments recieved.
  • va_arg: Retrieves the next value in the va_list with the type passed as the parameter.
  • va_end: Clean up the argument list.
Leap Year

Asked In: Zoho


If you are facing any issue on this page. Please let us know.